package cz.schovjan.mte_proj.task;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import cz.schovjan.mte_proj.Constant;
import cz.schovjan.mte_proj.R;
import cz.schovjan.mte_proj.dto.LyricResult;
import cz.schovjan.mte_proj.service.Searcher;
import cz.schovjan.mte_proj.service.SearcherImpl;

public class SearchLyricTask extends AsyncTask<String, Void, List<LyricResult>> {

    private ProgressDialog waiter = null;
    private Searcher searcher = null;
    private ListView lv = null;
    private Activity activity = null;


    public SearchLyricTask(Activity a, ListView lv) {
	this.lv = lv;
	this.activity = a;
	searcher = new SearcherImpl();
    }


    @Override
    protected List<LyricResult> doInBackground(String... params) {
	try {
	    Log.i(Constant.TAG, "spoustim vyhledavani textu");
	    List<LyricResult> ls = null;
	    switch (params.length) {
		case 1:
		    ls = searcher.byTextContain(params[0]);
		    break;
		case 2:
		    ls = searcher.byArtistSong(params[0], params[1]);
		    break;
		default:
		    break;
	    }
	    Log.i(Constant.TAG, "stazeno " + ls.size());
	    return ls;
	} catch (Exception e) {
	    e.printStackTrace();
	    return new ArrayList<LyricResult>();
	}
    }


    @Override
    protected void onPostExecute(List<LyricResult> result) {
	if (waiter != null) {
	    waiter.dismiss();
	}
	lv.setAdapter(new ArrayAdapter<LyricResult>(activity, android.R.layout.simple_list_item_1, result));
    }


    @Override
    protected void onPreExecute() {
	waiter = ProgressDialog.show(activity, activity.getResources().getString(R.string.wait_please), activity
		.getResources().getString(R.string.loadnig_diata));
    }
}
